import {
  Space,
  Button,
  Table,
  Tag,
  Dropdown,
  Tooltip,
  Input,
  Tabs,
  Modal,
  Drawer,
  Collapse,
  message,
  Popconfirm,
  Row,
  Col,
} from "antd";
import {
  EditOutlined,
  SnippetsOutlined,
  FilterOutlined,
  PlaySquareOutlined,
  PlusCircleOutlined,
  RightSquareOutlined,
  PlayCircleOutlined,
  CaretRightOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import React, { useState, useEffect, useRef } from "react";
import MyTitle from "@/components/MyTitle.jsx";
import TemplateForm from "@/views/generator/TemplateForm.jsx";
import API from "@/api/CgApi.js";
import AdvanceSearch from "@/views/generator/AdvanceSearch.jsx";
import axios from "axios";
const { Search } = Input;
const { Panel } = Collapse;
const { TextArea } = Input;
export default function () {
  const mounted = useRef(true);
  // loading
  const [loading, setLoading] = useState(true);
  const [keyWord, setKeyWord] = useState("");
  const [editId, setEditId] = useState("");

  const generateType = useRef("");
  // ============================================== table =====================================================

  // 表格数据
  const [tableData, setTableData] = useState([]);
  // 表格分页信息
  // const [pagination,setPagination] = useState({
  //   current:1,
  //   pageSize:5,
  //   showSizeChanger:true,
  //   showTotal: total => `Total ${total} items`,
  //   pageSizeOptions:[5,10,20,50,100],
  //   total:0
  // })

  // 表格分页信息和排序
  const [tableParams, setTableParams] = useState({
    pagination: {
      current: 1,
      pageSize: 10,
      showSizeChanger: true,
      showTotal: (total) => `Total ${total} items`,
      pageSizeOptions: [5, 10, 20, 50, 100],
    },

    sort: {
      sortField: "id",
      sortOrder: "desc",
    },
  });

  const tableParamsTemp = useRef({
    current: 1,
    pageSize: 10,
    sortField: "id",
    sortOrder: "desc",
  });

  const fetchDataForSearch = function (keyWord) {
    let queryParam = {};

    queryParam = { name: keyWord };

    fetchData(queryParam, true);
  };

  const advanceSearch = function (data) {
    fetchData(data, true);
    closeDraw();
  };

  // 表格查询
  const fetchData = function (queryCondition, clearPage) {
    console.log("queryCondition", queryCondition);
    if (clearPage) {
      tableParamsTemp.current.current = 1;
    }

    const queryParams = {
      ...tableParamsTemp.current,
    };

    if (queryCondition) {
      tableParamsTemp.current = {
        ...tableParamsTemp.current,
        ...queryCondition,
      };
    }

    if (
      !tableParamsTemp.current.sortField ||
      !tableParamsTemp.current.sortOrder
    ) {
      tableParamsTemp.current.sortField = null;
      tableParamsTemp.current.sortOrder = null;
    }

    // 后端分页的参数是pageNum,前端是current,这里进行转换
    tableParamsTemp.current.pageNum = tableParamsTemp.current.current;
    // alert(v)
    // const queryParams={};
    API.queryTemplate(tableParamsTemp.current).then((r) => {
      setTableData(r.result.list);
      setLoading(false);

      setTableParams({
        ...tableParams,
        pagination: {
          ...tableParams.pagination,
          total: r.result.total,
          showTotal: (total) => `Total ${total} items`,
          current: r.result.pageNum,
          pageSize: r.result.pageSize,
          // 200 is mock data, you should read it from server
          // total: data.totalCount,
        },
      });

      // if(pageSetting){
      //   setPagination({...pagination,...pageSetting,
      //     total:r.result.total
      //   })
      // }else{
      //   setPagination({...pagination,
      //     total:r.result.total
      //   })
      // }
    });
  };

  const saveData = (data) => {
    console.log(data);
    // 新增
    if (!data.id) {
      API.addGeneratorTemplate(data).then((r) => {
        console.log(r);
        message.success("操作成功");
        fetchData();
        closeForm();
      });
    } else {
      // 修改
      API.updateGeneratorTemplate(data).then((r) => {
        console.log(r);
        message.success("操作成功");
        fetchData();
        closeForm();
      });
    }
  };

  const deleteData = (id) => {
    API.deleteGeneratorTemplate(id).then((r) => {
      console.log(r);
      message.success("操作成功");
      fetchData();
    });
  };

  // 表格翻页/改变每页条目数
  const handleTableChange = (pagination, filters, sorter) => {
    console.log(pagination, sorter);
    const { current, pageSize } = pagination;
    tableParamsTemp.current = { ...tableParamsTemp, current, pageSize };

    const { field, order } = sorter;
    if (field) {
      tableParamsTemp.current.sortField = field;
    }

    if (order) {
      tableParamsTemp.current.sortOrder = order.replace("end", "");
    }

    fetchData();
  };

  // 表格字段设置
  const columns = [
    {
      title: "Project",
      dataIndex: "project",
      key: "project",
      render: (text, record) => <a>{record.project}</a>,
      sorter: true,
    },
    {
      title: "Name",
      dataIndex: "name",
      key: "name",
      sorter: true,
    },
    {
      title: "Classify",
      dataIndex: "classify",
      key: "classify",
      sorter: true,
    },

    {
      title: "Action",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Space>
            <Tooltip title="Edit Template" placement="top">
              <a>
                <EditOutlined
                  onClick={function () {
                    operateData(record);
                    openForm();
                  }}
                />
              </a>
            </Tooltip>

            {/* <Tooltip title="Generator Code" placement="top">
              <a>
                <PlaySquareOutlined
                  onClick={function () {
                    operateData(record);
                    setGenerateType("DATA")
                    openCfg();
                  }}
                />
              </a>
            </Tooltip> */}

            <Popconfirm
              title="Are you sure to delete this record ?"
              onConfirm={function () {
                deleteData(record.id);
              }}
              okText="Yes"
              cancelText="No"
            >
              <a>
                <DeleteOutlined />
              </a>
            </Popconfirm>
          </Space>
        </Space>
      ),
    },
  ];

  const operateData = function (data) {
    setEditId(data.id);
  };

  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const onSelectChange = (newSelectedRowKeys) => {
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const [generateResult, setGenerateResult] = useState({});

  const generateCode = () => {
    // alert(generateType.current)
    console.log(selectedRowKeys);
    if (generateType.current == "ZIP") {
      // axios.post('http://127.0.0.1:3000/api/generatorTemplate/generateToZip',{
      //   tableNames:cfg.tableNames.split(";"),
      //   ids:selectedRowKeys
      // },{responseType: 'blob' }).then

      API.generateToZip({
        tableNames: cfg.tableNames.split(";"),
        ids: selectedRowKeys,
      }).then((res) => {
        console.log(res);
        let blob = new Blob([res]);
        let url = window.URL.createObjectURL(blob); // 创建 url 并指向 blob
        let a = document.createElement("a");
        a.href = url;
        a.download = "code.zip";
        a.click();
        window.URL.revokeObjectURL(url); // 释放该 url
      });
    } else if (generateType.current == "DATA") {
      API.generateToData({
        tableNames: cfg.tableNames.split(";"),
        ids: selectedRowKeys,
      }).then((res) => {
        console.log(res);
        setGenerateResult(res.result);
        closeCfg();
        openResult();
      });
    }

    // API.generateZip({
    //   tableName:cfg.tableName,
    //   ids:selectedRowKeys
    // }).then( res => {
    //   console.log(res);
    //   let blob = new Blob([res.data]);
    //   let url = window.URL.createObjectURL(blob); // 创建 url 并指向 blob
    //   let a = document.createElement('a');
    //   a.href = url;
    //   a.download = 'code.zip';
    //   a.click();
    //   window.URL.revokeObjectURL(url); // 释放该 url
    // })
  };

  const [formVisible, setFormVisible] = useState(false);
  const openForm = () => {
    setFormVisible(true);
  };

  const closeForm = () => {
    setFormVisible(false);
    setEditId(null);
  };

  const [cfgVisible, setCfgVisible] = useState(false);
  const openCfg = () => {
    setCfgVisible(true);
  };
  const closeCfg = () => {
    setCfgVisible(false);
  };

  const [cfg, setCfg] = useState({
    tableNames: "generator_template",
  });

  const [resultVisible, setResultVisible] = useState(false);
  const openResult = () => {
    setResultVisible(true);
  };
  const closeResult = () => {
    setResultVisible(false);
  };

  const [count, setCount] = useState(0); //初始值为0。
  const myArray = ["one", "two", "three"];

  // ============================================== search =====================================================
  const [open, setOpen] = useState(false);

  const closeDraw = () => {
    setOpen(false);
  };
  const openDraw = () => {
    setOpen(true);
  };

  // ============================================== componentDidMounted =====================================================
  useEffect(() => {
    // if(!mounted){

    // }else{
    //   mounted.current = false;
    // }

    fetchData();
  }, []);

  // const [a,setA] = useState(1)

  // useEffect(() => {
  //   console.log("useEffect")
  // }, [a]);

  return (
    <div>
      {/* { JSON.stringify(generateResult)} */}
      <Drawer
        title="Advance Search"
        width={320}
        closable={true}
        onClose={closeDraw}
        open={open}
      >
        <AdvanceSearch
          keyWord={keyWord}
          onClose={closeDraw}
          callback={advanceSearch}
        >
          <div>123</div>
        </AdvanceSearch>
      </Drawer>

      {/* <Button onClick={()=>{setA({name:Math.random(),age:Math.random()})}}>{a.name}</Button> */}
      {/* <div style={{ textAlign: "right", paddingRight: 8, lineHeight: "16px" }}>
        Code Generator 1.0
      </div> */}
      <div style={{ padding: 8 }}>
        <div style={{ padding: "8px 0px", display: "flex" }}>
          <div style={{ flex: "0 0 auto" }}>
            <MyTitle title="Template"></MyTitle>
            {/* <div style={{borderLeft:"4px solid #1890ff",height:24,paddingLeft:16,fontWeight:"bold",color:"#1890ff"}}> Template </div> */}
          </div>
          <div style={{ flex: "1 1 auto" }}></div>
          <div style={{ flex: "0 0 auto", textAlign: "right" }}>
            <Space>
              <Search
                placeholder="input search text"
                onSearch={(v) => {
                  fetchDataForSearch(v, false);
                }}
                onChange={(v) => {
                  setKeyWord(v.target.value);
                }}
                style={{ width: 200 }}
              />

              <Button onClick={openDraw} icon={<FilterOutlined />}></Button>

              <Tooltip title="Generator Code Batch" placement="leftTop">
                <Button
                  type="primary"
                  danger
                  icon={<SnippetsOutlined />}
                  disabled={selectedRowKeys.length == 0}
                  onClick={() => {
                    openCfg();
                  }}
                ></Button>
              </Tooltip>

              <Tooltip title="Create A Template" placement="leftTop">
                <Button
                  type="primary"
                  icon={<PlusCircleOutlined />}
                  onClick={function () {
                    setEditId(null);
                    openForm();
                  }}
                ></Button>
              </Tooltip>
            </Space>
          </div>
        </div>
        <Table
          size={"small"}
          rowKey={(record) => record.id}
          rowSelection={rowSelection}
          dataSource={tableData}
          columns={columns}
          pagination={tableParams.pagination}
          onChange={handleTableChange}
        ></Table>
      </div>
      <Modal
        width="100%"
        maskClosable={false}
        style={{ top: 16 }}
        title={<MyTitle title="Template Information"></MyTitle>}
        footer={null}
        open={formVisible}
        destroyOnClose={true}
        onCancel={closeForm}
      >
        <TemplateForm
          callback={closeForm}
          saveData={saveData}
          editId={editId}
        ></TemplateForm>
      </Modal>
      <Modal
        style={{ top: 16 }}
        maskClosable={false}
        title={<MyTitle title="Configuration"></MyTitle>}
        footer={null}
        open={cfgVisible}
        destroyOnClose={true}
        onCancel={closeCfg}
      >
        <dl>
          <dt>Table Names (More table use ";" split)</dt>
          <dd>
            <Input
              value={cfg.tableNames}
              onChange={(e) => {
                setCfg({ ...cfg, tableNames: e.target.value });
              }}
            ></Input>{" "}
          </dd>
        </dl>

        <Row gutter={24}>
          <Col span={12}>
            <Button
              block
              type="primary"
              onClick={() => {
                generateType.current = "ZIP";
                generateCode();
              }}
            >
              Generate Code To Zip
            </Button>
          </Col>
          <Col span={12}>
            <Button
              block
              type="primary"
              onClick={() => {
                generateType.current = "DATA";
                generateCode();
              }}
            >
              Generate Code To Data
            </Button>
          </Col>
        </Row>
      </Modal>

      <Modal
        style={{ top: 16 }}
        width="100%"
        maskClosable={false}
        title={<MyTitle title="Result"></MyTitle>}
        open={resultVisible}
        destroyOnClose={false}
        onOk={closeResult}
        onCancel={closeResult}
      >
        <Collapse defaultActiveKey={0}>
          {Object.entries(generateResult).map(([key, value], idx) => {
            return (
              <Panel header={idx + 1 + "." + key} key={idx}>
                <Tabs defaultActiveKey={0} tabPosition="left">
                  {value.map((item, idx2) => {
                    return (
                      <Tabs.TabPane tab={item.fileName} key={idx2}>
                        <TextArea
                          value={item.content}
                          autoSize={{ minRows: 3 }}
                        ></TextArea>
                      </Tabs.TabPane>
                    );
                  })}
                </Tabs>
              </Panel>
            );
          })}
        </Collapse>
      </Modal>
    </div>
  );
}
